package com.wb.base;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.Unbinder;


public abstract class BaseFragment extends Fragment {


    public String getTitle() {
        return "";
    }

    private View rootView;

    private Unbinder unbinder;
    private boolean isCreateData = false;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(getContentView(), container, false);
        unbinder = ButterKnife.bind(this, rootView);
        initView();

        initListener();
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        init();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        init();
    }

    private void init() {
        if (isAdded() && !isHidden()) {
            if (!isCreateData) {
                synchronized (BaseFragment.class) {
                    if (!isCreateData) {
                        initData();
                        isCreateData = true;
                    }
                }
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    protected abstract int getContentView();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void initListener();

    public <T extends View> T findViewById(int resId) {
        return (T) rootView.findViewById(resId);
    }

    public View getRootView() {
        return rootView;
    }

    public <T extends View> T $(@IdRes int resId) {
        return (T) rootView.findViewById(resId);
    }

    public void click(View.OnClickListener listener, @IdRes int resId) {
        $(resId).setOnClickListener(listener);
    }

    public void click(View.OnClickListener listener, int... resIds) {
        for (int resId : resIds
                ) {
            $(resId).setOnClickListener(listener);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}

